package com.tanhua.server.service;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.domain.UserInfo;
import com.tanhua.dto.RecommendUserDto;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.mongo.RecommendUser;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    public TodayBest queryWithMaxScore() {
        //获取当前用户的登录的id
        Long userId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        UserInfo userInfo = userInfoApi.getById(recommendUser.getToUserId());
        TodayBest todayBest = TodayBest.init(userInfo,recommendUser);
        return todayBest;
    }

    public PageResult recommendation(RecommendUserDto dto) {
        //获取当前用户的登录的id
        Long userId = UserHolder.getUserId();
        //根据用户id,分页查询出
        PageResult pr = recommendUserApi.queryRecommendUserList(userId,dto.getPage(),dto.getPagesize());

        //获取推荐用户的集合
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if (items == null){
            return pr;
        }
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        //所有推荐的用户的基本数据
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, userInfo);

        List<TodayBest> list = new ArrayList<>();
        //根据用户id,从map中获取每个用户 的基本数据
        for (RecommendUser item : items) {
            Long id = item.getUserId();
            UserInfo user = infoMap.get(id);
            if (user != null){
                TodayBest todayBest = TodayBest.init(user, item);
                list.add(todayBest);
            }
        }

        /*List<TodayBest> list= items.stream().map((item)->{
            Long id = item.getUserId();
            UserInfo userInfo = userInfoApi.getById(id);
            TodayBest todayBest = null;
            if (userInfo != null){
                todayBest = TodayBest.init(userInfo, item);
            }
            return todayBest;
        }).collect(Collectors.toList());
*/
        pr.setItems(list);
        return pr;
    }
}
